<template>
  <div class="tab-bar-item" @click="itemClick">
    <div :class="itemActive">
      <slot :name="iconActive" />
    </div>
    <div class="item-text" :style="activeStyle">
      <slot name="text"/>
    </div>
    <div class="tag" v-show="path === 'cart' && goodsNum > 0">
      {{ goodsNum }}
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  name: 'TabBarItem',
  props: {
    path: {
      type: String,
      required: true
    }
  },
  computed: {
    itemActive () {
      return this.isActive ? 'item-active-icon' : 'item-icon'
    },
    iconActive () {
      return this.isActive ? 'active-icon' : 'normal-icon'
    },
    isActive () {
      return this.$route.path.includes(this.path)
    },
    activeStyle () {
      return this.isActive ? { color: 'red' } : {}
    },
    goodsNum () {
      const goodsNum = Object.values(this.shopCart).reduce((total, cur) => total + cur.num, 0)
      return goodsNum
    },
    ...mapGetters([
      'shopCart'
    ])
  },
  methods: {
    itemClick () {
      this.$router.replace(this.path)
    }
  }
}

</script>
<style lang='scss' scoped>
.tab-bar-item {
  position: relative;
  flex: 1;
  .item-icon img, .item-active-icon img {
    width: px2rem(24);
    height: px2rem(24);
    margin-top: px2rem(5);
    vertical-align: middle;
  }
  .item-text {
    font-size: px2rem(12);
    margin-top: px2rem(3);
    color: #333;
  }
  .tag {
    position: absolute;
    top: px2rem(1);
    right: px2rem(36);
    background: $theme-color-red;
    @include setFontColor(px2rem(12), $text-color-white);
    min-width: px2rem(16);
    padding: 0 px2rem(3);
    line-height: px2rem(14);
    text-align: center;
    border: 1px solid $text-color-white;
    font-weight: 500;
    border-radius: px2rem(16);
    transform: translateX(50%);
    transform-origin: 100%;
  }
}
</style>
